const express = require('express');
const { ObjectId } = require('mongodb');
const { getBookmarkCollection } = require('./database');

const router = express.Router();

// 中间件，用于获取 bookmarkCollection
router.use(async (req, res, next) => {
    req.bookmarkCollection = await getBookmarkCollection();
    next();
});

// 创建书签
router.post('/bookmarks', async (req, res) => {
    try {
        const { favIconUrl, title, url, describe = '' } = req.body;
        const result = await req.bookmarkCollection.insertOne({ favIconUrl, title, url, describe });
        res.status(201).json({ message: 'Bookmark created successfully', bookmarkId: result.insertedId });
    } catch (err) {
        console.error(err);
        res.status(500).json({ message: 'Error creating bookmark', error: err.message });
    }
});

// 更新书签
router.put('/bookmarks/:id', async (req, res) => {
    try {
        const { favIconUrl, title, url, describe } = req.body;
        const result = await req.bookmarkCollection.updateOne(
            { _id: new ObjectId(req.params.id) },
            { $set: { favIconUrl, title, url, describe } }
        );
        if (result.matchedCount === 0) {
            return res.status(404).json({ message: 'Bookmark not found' });
        }
        res.json({ message: 'Bookmark updated successfully' });
    } catch (err) {
        console.error(err);
        res.status(500).json({ message: 'Error updating bookmark', error: err.message });
    }
});

// 获取所有书签（带分页）
router.get('/bookmarks', async (req, res) => {
    try {
        const page = parseInt(req.query.page) || 1;
        const limit = parseInt(req.query.limit) || 10;
        const skip = (page - 1) * limit;

        const totalBookmarks = await req.bookmarkCollection.countDocuments();
        const bookmarks = await req.bookmarkCollection.find()
            .skip(skip)
            .limit(limit)
            .toArray();

        res.json({
            bookmarks,
            currentPage: page,
            totalPages: Math.ceil(totalBookmarks / limit),
            totalBookmarks
        });
    } catch (err) {
        console.error(err);
        res.status(500).json({ message: 'Error fetching bookmarks', error: err.message });
    }
});

// 获取特定书签
router.get('/bookmarks/:id', async (req, res) => {
    try {
        const bookmark = await req.bookmarkCollection.findOne({ _id: new ObjectId(req.params.id) });
        if (!bookmark) {
            return res.status(404).json({ message: 'Bookmark not found' });
        }
        res.json(bookmark);
    } catch (err) {
        console.error(err);
        res.status(500).json({ message: 'Error fetching bookmark', error: err.message });
    }
});

// 删除书签
router.delete('/bookmarks/:id', async (req, res) => {
    try {
        const result = await req.bookmarkCollection.deleteOne({ _id: new ObjectId(req.params.id) });
        if (result.deletedCount === 0) {
            return res.status(404).json({ message: 'Bookmark not found' });
        }
        res.json({ message: 'Bookmark deleted successfully' });
    } catch (err) {
        console.error(err);
        res.status(500).json({ message: 'Error deleting bookmark', error: err.message });
    }
});

module.exports = router;